package com.mlf;

import com.mlf.observer.demo01.TemperatureAlarm;
import com.mlf.observer.demo01.TemperatureDisplay;
import com.mlf.observer.demo01.TemperatureSensor;

import java.util.Scanner;

public class ObserverDemo1 {

    public static void main(String[] args) {
        // 创建被观察者 - 主题
        TemperatureSensor sensor = new TemperatureSensor();

        // 创建观察者
        TemperatureDisplay temperatureDisplay = new TemperatureDisplay("温度显示器");
        TemperatureDisplay temperatureDisplay2 = new TemperatureDisplay("温度显示器2");
        TemperatureAlarm temperatureAlarm = new TemperatureAlarm();

        // 注册观察者
        sensor.addObserver(temperatureDisplay);
        sensor.addObserver(temperatureDisplay2);
        sensor.addObserver(temperatureAlarm);

        System.out.println("温度传感器开始工作...");
        Scanner scanner = new Scanner(System.in);
        while (true) {
            System.out.println("请输入温度:");
            String s = scanner.nextLine();
            if ("exit".equals(s)) {
                break;
            }
            try {
                double temp = Double.parseDouble(s);
                sensor.setTemperature(temp);
            } catch (NumberFormatException e) {
                throw new RuntimeException("请输入有效数字！");
            }
        }

        scanner.close();
        System.out.println("系统已关闭");
    }
}
